import SwiftUI

struct AllTransactionsView: View {
    @EnvironmentObject var expenseStore: ExpenseStore
    @Environment(\.dismiss) private var dismiss

    @State private var animate = false

    var sortedExpenses: [Expense] {
        expenseStore.expenses.sorted { $0.amount > $1.amount }
    }

    var body: some View {
        ScrollView(showsIndicators: false) {
            VStack(spacing: 18) {

                VStack(spacing: 6) {
                    Text("All Transactions")
                        .font(.largeTitle.bold())

                    Text("\(sortedExpenses.count) total")
                        .foregroundColor(.secondary)
                }
                .padding(.top, 10)
                .opacity(animate ? 1 : 0)
                .offset(y: animate ? 0 : 20)
                .animation(.easeOut(duration: 0.5), value: animate)

                VStack(spacing: 14) {
                    ForEach(Array(sortedExpenses.enumerated()), id: \.element.id) { index, expense in
                        TransactionCard(expense: expense)
                            .padding(.horizontal)
                            .opacity(animate ? 1 : 0)
                            .offset(y: animate ? 0 : 10)
                            .animation(
                                .spring(response: 0.45, dampingFraction: 0.8)
                                    .delay(0.03 * Double(index)),
                                value: animate
                            )
                    }
                }
                .padding(.top, 12)

                Spacer(minLength: 40)
            }
        }
        .navigationTitle("View All")
        .navigationBarTitleDisplayMode(.inline)
        .onAppear { animate = true }
        .background(
            LinearGradient(
                colors: [
                    Color(.systemGray6),
                    Color(.systemGray5).opacity(0.5),
                    Color.white
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .ignoresSafeArea()
        )
    }
}
